using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Util;

namespace Geekeradmin.ExtendsService
{
    public class ClearLogService : BackgroundService
    {
        private readonly IMySqlSugarService mySqlSugar;

        private static bool isCanDelete = true;

        /// <summary>
        /// 初始化依赖注入
        /// </summary>
        /// <param name="mySqlSugar"></param>
        public ClearLogService(IMySqlSugarService mySqlSugar)
        {
            this.mySqlSugar = mySqlSugar;
        }

        public override async Task StartAsync(CancellationToken cancellationToken)
        {
            await base.StartAsync(cancellationToken);
        }

        public override async Task StopAsync(CancellationToken cancellationToken)
        {
            await base.StopAsync(cancellationToken);
        }

        public override void Dispose() { }

        /// <summary>
        ///
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Delay(6000, stoppingToken); //启动后一分钟执行一次
            InitTask();
        }

        private void InitTask()
        {
            Task.Factory.StartNew(() =>
            {
                var clogtb = TableAtributeUtil.GetTable<Controllerexelog>();
                var sptb = TableAtributeUtil.GetTable<Spconf>();
                while (true)
                {
                    if (DateTime.Now.Hour == 0 && isCanDelete)
                    {
                        isCanDelete = false;
                        var LogDayDelete = 190;
                        var sql = $"select sValue from {sptb} where sCode='LogDayDelete' and status=1;";
                        var list = this.mySqlSugar.Query<Spconf>(sql, null, out var msg);
                        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
                        {
                            var sValue = list.FirstOrDefault().sValue.GetIntValue();
                            if (sValue >= 190)
                            {
                                LogDayDelete = sValue;
                            }
                        }
                        var deleteTime = DateTime.Now.AddDays(-LogDayDelete).ToString("yyyy-MM-dd HH:mm:ss");
                        sql = $"delete from {clogtb} where cTime<='{deleteTime}';";
                        this.mySqlSugar.ExecuteSql(sql, null, out msg);
                    }

                    if (DateTime.Now.Hour == 23 && DateTime.Now.Minute > 58)
                    {
                        isCanDelete = true;
                    }
                    Thread.Sleep(12000);
                }
            });
        }
    }
}
